package com.adam.framework.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import junit.framework.TestCase;

import com.adam.framework.connectionpool.MyDataSource;

public class JdbcTemplateTestCase extends TestCase {

	private JdbcTemplate jdbcTemplate = null;

	protected void setUp() throws Exception {
		super.setUp();
		jdbcTemplate = new JdbcTemplate(MyDataSource.getInstance());
	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void testSelectCount() {
		assertEquals(5, this.jdbcTemplate
				.queryForInt("select count(0) from TCLM_USER"));
	}

	public void testQueryByOneColumn() {
		int count = this.jdbcTemplate.queryForInt(
				"select count(0) from tclm_user where username = ?",
				new Object[] { "Joe" });
	}

	public void testQueryForString() {
		String surname = (String) this.jdbcTemplate.queryForObject(
				"select first_name from tclm_user where username = ?",
				new Object[] { "tom" }, String.class);
	}

	public void testSingleDomain() {
		User user = (User) this.jdbcTemplate.queryForObject(
				"select * from tclm_user where username = ?",
				new Object[] { "tom" }, new RowMapper() {
					public Object mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						User user = new UserImpl();
						user.setUserName(rs.getString("username"));
						user.setEmail(rs.getString("email"));
						return user;
					}
				});
	}

	public void testMultipleDomain() {
		Collection users = this.jdbcTemplate.query(
				"select username, email from tclm_user", new RowMapper() {
					public Object mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						User actor = new UserImpl();
						actor.setUserName(rs.getString("username"));
						actor.setEmail(rs.getString("email"));
						return actor;
					}
				});
	}

	public void testInsert() {
		this.jdbcTemplate.update(
				"insert into tclm_user (username, first_name, sur_name, email, create_time)"
						+ " values (?, ?, ?, ?, ?)", new Object[] { "marlene",
						"Leonor", "Watling", "Leonor@tom.com",
						new java.sql.Date(new java.util.Date().getTime() )});
	}

}
